<?php
// +----------------------------------------------------------------------
// | WWW.0771MC.COM 广西南宁市铭成龙毅网络科技有限公司 出品
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://WWW.0771MC.COM All rights reserved.
// +----------------------------------------------------------------------
// | Author: 铭成龙毅 <service@0771mc.com> <http://www.0771MC.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Think\Controller;
class ModelController extends CommonController {



    public function index(){
        $this->vlist = M('model')->order('sort')->select();
        $this->display();
    }

    public function add() { 
        if (IS_POST) {
            $this->addHandle();
            exit();
        }   
        $this->styleListList = getFileFolderList(APP_PATH.C('DEFAULT_MODULE').'/View/'.C('cfg_theme').'/List/' , 2, 'List_*');
        $this->styleShowList = getFileFolderList(APP_PATH.C('DEFAULT_MODULE').'/View/'.C('cfg_theme').'/Show/' , 2, 'Show_*');
        $this->display();
    }

    public function addHandle() {

        $name=I('post.name');
        $tablename=I('post.tablename');
        $tablename=strtolower($tablename);
        if (empty($name)||empty($tablename)) {
           error('模型名称或者表名不能为空！');
        }
        $is_use=M('model')->where(array('tablename'=>$tablename))->count();
        if ($is_use) {
           error('模型表已存在！');
        }
        $db=M();
        $full_table=C('DB_PREFIX').$tablename;
        $query = "SHOW TABLES FROM ".C('DB_NAME');
        $Tables="Tables_in_".C('DB_NAME');
        $row=$db->query($query);
        for ($i=0; $i <count($row) ; $i++) { 
            if ($row[$i][$Tables]==$full_table) {
                error('指定的表在数据库中重复');
            }
        }
        $addtable="addon".$tablename;
        $sql = "CREATE TABLE IF NOT EXISTS  `$full_table`(
                `id` int(10) unsigned NOT NULL auto_increment,
                `title` varchar(100) NOT NULL default '',
                `cid` int(11) UNSIGNED NOT NULL DEFAULT '0',
                `click` INT( 10 ) UNSIGNED NOT NULL DEFAULT '0',
                `shorttitle` varchar(60) NOT NULL default '',
                `litpic` varchar(150) NOT NULL default '',
                `color` char(10) NOT NULL default '',
                `copyfrom` varchar(45) NOT NULL default '',
                `author` varchar(45) NOT NULL default '',
                `keywords` varchar(60) NOT NULL default '',
                `description` varchar(255) NOT NULL default '',
                `publishtime` INT( 10 ) UNSIGNED NOT NULL DEFAULT '0',
                `updatetime` INT( 10 ) UNSIGNED NOT NULL DEFAULT '0',
                `commentflag` tinyint(1) NOT NULL default '1',
                `flag` varchar(50) NOT NULL default '',
                `jumpurl` varchar(200) NOT NULL default '',
                `status` tinyint(1) NOT NULL default '0',
                `userid` int(11) UNSIGNED NOT NULL DEFAULT '0',
                `aid` int(11) UNSIGNED NOT NULL DEFAULT '0',
                `addtable` varchar(60) NOT NULL default '$addtable',
                ";
        $full_addtable=C('DB_PREFIX').$addtable;
        $sql_addon="CREATE TABLE IF NOT EXISTS  `$full_addtable`(
            `aid` int(11) NOT NULL DEFAULT '0',
            ";
        $mysql_version = $db->query("select version() as ver");
        if($mysql_version[0]['ver'] < 4.1)
        {
            $sql .= " PRIMARY KEY  (`id`)\r\n) TYPE=MyISAM; ";
            $sql_addon .= " PRIMARY KEY  (`aid`)\r\n) TYPE=MyISAM; ";
        }else{
            $sql .= " PRIMARY KEY  (`id`)\r\n) ENGINE=MyISAM DEFAULT CHARSET=".C('DB_CHARSET')."; ";
            $sql_addon .= " PRIMARY KEY  (`aid`)\r\n) ENGINE=MyISAM DEFAULT CHARSET=".C('DB_CHARSET')."; ";
        }
        $db->query($sql);
        $db->query($sql_addon);
        $data=array(
            'name'=>$name,
            'description'=>I('post.description'),
            'tablename'=>$tablename,
            'status'=>I('post.status'),
            'template_category'=>I('post.template_category'),
            'template_list'=>I('post.template_list'),
            'template_show'=>I('post.template_show'),
            'sort'=>I('post.sort')
        );
        if(M('model')->add($data)){
            yes('添加成功！',true,'Model-index');
        }else{
            error('添加失败');
        }
        
    }

    /*
   <field:xingbie itemname="性别" autofield="1" notsend="0" type="radio" isnull="true" islist="0" default="男,女"  maxlength="250" page="">
    </field:xingbie>
    name=xingbie itemname="性别" type="radio" isnull="true" default="男,女" maxlength="250"|
     */
    public function fieldset(){
        if (IS_POST) {
            # code...
        }else{
            $model_id=I('get.id',0,'intval');
            if ($model_id==0) {
                error('参数错误！');
            }
           // $fields=M('model')->where(array('id'=>$model_id))->getField('fieldset');
           // $fields=explode('|', $fields);
            $fields=M('model_field')->where(array('model_id'=>$model_id))->select();
            $this->fields=$fields;
            $this->model_id=$model_id;
            $this->display();
        }
    }

    public function addfieldset(){
        if(IS_POST){
            $model_id=I('post.model_id',0,'intval');
            $vdefault=I('post.vdefault');
            $maxlength=I('post.maxlength');
            $dtype=I('post.dtype');
            $fieldname=I('post.fieldname');
            $itemname=I('post.itemname');
            $sort=I('post.sort');

            if ($model_id==0) {
                error('参数错误！');
            }
            
            if (empty($itemname)||empty($fieldname)) {
                error('表单提示文字或字段名称不能为空！');
            }
            $main_table_fileds=array(
                'id','title','cid','click','shorttitle','litpic','color','copyfrom','author','keywords','description','publishtime','updatetime','commentflag','flag','jumpurl','status','userid','aid','addtable','aid'
            );
            if (in_array($filename,$main_table_fileds)) {
                error('字段已经被占用！');;
            }

            if(preg_match("#^(select|radio|checkbox)$#i", $dtype))
            {
                if(!preg_match("#,#", $vdefault))
                {
                    error("你设定了字段为 {$dtype} 类型，必须在默认值中指定元素列表，如：'a,b,c' ");
                }
            }

            $addtable=M('model')->where(array('id'=>$model_id))->getField('tablename');

            $addtable_fields=M("addon".$addtable)->getDbFields();
            for ($i=0; $i <count($addtable_fields) ; $i++) { 
                if ($addtable_fields[$i]==$fieldname) {
                    error('已经存在该字段名称！');
                }
            }
            $fieldinfos=GetFieldMake($dtype, $fieldname, $vdefault, $maxlength);
            $ntabsql = $fieldinfos[0];
            $buideType = $fieldinfos[1];
            $db=M();
            $trueTable=C('DB_PREFIX')."addon".$addtable;
            $sql=" ALTER TABLE `$trueTable` ADD  $ntabsql ";
            $db->query($sql);

            //储存字段信息到 模型字段表
            $model_field=array(
                    'model_id'=>$model_id,
                    'field'=>$fieldname,
                    'itemname'=>$itemname,
                    'default_value'=>$vdefault,
                    'type'=>$dtype,
                    'sort'=>$sort
                );
            $is_add=M('model_field')->add($model_field);
            if ($is_add) {
                yes('添加字段成功！',true,'model-fieldset');
            }else{
                error('字段添加失败！');
            }
        }else{
            $model_id=I('get.model_id',0,'intval');
            $this->model_id=$model_id;
            $this->display();
        }
    }

    //
    public function editfieldset(){
        if (IS_POST) {
            $data = array(
                'id' => I('post.id'),
                'type' => I('post.dtype'),
                'itemname' => I('post.itemname'),
                'sort' => I('post.sort'),
                'default_value' => I('post.vdefault')
                 );
            $is_sucess=M('model_field')->save($data);
            if ($is_sucess) {
                yes('修改字段成功！',true,'model-fieldset');
            }else{
                error('字段添加失败！',true);
            }
        }else{
            $model_id=I('get.id',0,'intval');
            $field=M('model_field')->where(array('id'=>$model_id))->find();
            $this->field=$field;
            $this->display();
        }
    }

    //
    public function delfieldset(){
        $id=I('get.id');
        $mid=I('get.mid');
        $addon_table=M('model')->where(array('id'=>$mid))->getField('tablename');
        $db=M();
        $addon_table=C('DB_PREFIX')."addon".$addon_table;
        $ziduan=M('model_field')->where(array('id'=>$id))->getField('field');
        $sql="ALTER TABLE `$addon_table` DROP `$ziduan` ";
        $db->query($sql);
        $is_del=M('model_field')->where(array('id'=>$id))->delete();
        if ($is_del) {
            yes('删除字段成功！');
        }else{
            error('删除字段失败！');
        }
    }

    //编辑
    public function edit() {
        if (IS_POST) {
            $this->editHandle();
            exit();
        }
        $id = I('id', 0, 'intval');
        $data = M('model')->find($id);
        if (!$data) {
            $this->error('记录不存在');
        }
        $this->vo = $data;          
        $this->styleListList = getFileFolderList(APP_PATH.C('DEFAULT_MODULE').'/View/'.C('cfg_theme').'/List/' , 2, 'List_*');
        $this->styleShowList = getFileFolderList(APP_PATH.C('DEFAULT_MODULE').'/View/'.C('cfg_theme').'/Show/' , 2, 'Show_*');
        $this->display();
    }



    //修改分类处理

    public function editHandle() {

        $id = I('id',0, 'intval');
        $name = I('name', '', 'trim');
        $tablename = I('tablename', '', 'trim');
        $template_list = I('template_list', '', 'trim');
        $template_show = I('template_show', '', 'trim');

        if (empty($name)) {
            $this->error('模型名称不能为空！');
        }
        if (empty($template_list)) {
            $this->error('请选择列表模板');
        }
        if (empty($template_show)) {
            $this->error('请选择内容页模板');
        }

        if (M('model')->where(array('id' => array('neq', $id), array('tablename' => $tablename ,'name' => $name, '_logic' => 'OR')))->find()) {
            $this->error('模型名称或附加表已经存在！');
        }

        if (false !== M('model')->save($_POST)) {
            //$this->success('修改成功',U('Model/index'));
            yes('修改成功！',true,'Model-index');
        }else {
            $this->error('修改失败');
        }
        
    }

    //批量更新排序
    public function sort() {
        foreach ($_POST as $k => $v) {
            if ($k == 'key') {
                continue;
            }
            M('model')->where(array('id'=>$k))->setField('sort',$v);
        }
        yes();
    }

    public function del() {
        $id = I('id',0,'intval');
        if ($id==0) {
            error('参数错误！');
        }
        $db=M('model')->where(array('id'=>$id))->getField('tablename');
        $full_db=C('DB_PREFIX').$db;
        $addtable=C('DB_PREFIX')."addon".$db;
        $sql="DROP TABLE IF EXISTS `$full_db`;";
        $sql_addon="DROP TABLE IF EXISTS `$addtable`;";
        M('model_field')->where(array('model_id'=>$id))->delete();
        $model=M();
        $model->query($sql);
        $model->query($sql_addon);
        if (M('model')->delete($id)) {
            yes('删除成功！');
        }else {
            $this->error('删除失败');
        }
    }

}